import React from 'react'
import { DeviceEventEmitter } from 'react-native'
import { connect } from 'react-redux'

import BaseHomePage from 'src/pageP/home/home-page/index2'
import { cancelCollectionPost, collectionPost, getPostDetail, homePostList } from 'src/utils/RequestAPI'
import JobCell from 'src/components/job-cell/index2'
import CustomButton from 'src/components/button/CustomButton'
import { C_POSITION_REFRESH } from 'src/pageC/tabbar'
import RefreshState from 'src/components/custom-flat-list/RefreshState'
import { IS_ANDROID, ScaleS } from 'src/utils/ScreenUtil'
import { showModal } from 'src/utils/ModalUtil'
import BackHandlerUtil from 'src/utils/BackHandlerUtil'

const defaultPositionCategory = '全部'

const mapActiontoProps = dispatch => ({})

@connect(
  ({ landmark, userinfo }) => ({
    landmark,
    userId: userinfo.userId,
    role: userinfo.role
  }),
  mapActiontoProps
)
class CPositionPage extends BaseHomePage {
  constructor (props) {
    super(props)
    this.pageType = 'C'
    this.pageKey = 'page'
    this.cityNameKey = 'city'
    this.categoryKey = 'category'
    this.areaKey = 'area'
    this.orderKey = 'order'
    this.homeListParams = this._getHomeListParams()
    this.orderLabel = [
      {
        isAll: true,
        label: '推荐',
        type: this.orderKey,
        value: 'order'
      },
      {
        isAll: false,
        label: '最新',
        type: this.orderKey,
        value: 'order'
      },
      {
        isAll: false,
        label: '最近',
        type: this.orderKey,
        value: 'distance'
      }
    ]
    this.dotArr = [
      {
        label: '举报',
        type: 0
      },
      {
        label: '关注',
        type: 1
      },
      {
        label: '取消关注',
        type: 2
      },
      {
        label: '不感兴趣',
        type: 3
      }
    ]
    this._positionNavigation()
  }

  /**
   * 职位导航
   * @private
   */
  _positionNavigation = () => {
    const { navigation } = this.props
    const position = navigation.getParam('position', null)
    if (position) {
      const { type, category } = position
      this.currentIndex = type
      const filterArr = this._reInitFilterArr(category)
      this._setPositionFilterArr(filterArr)
      this._setCategoryParam(category)
    }
  }

  /**
   * 设置职位的过滤条件
   * @param filterArr
   * @private
   */
  _setPositionFilterArr = (filterArr) => {
    this.state = {
      ...this.state,
      index: this.currentIndex,
      filterArr
    }
  }

  /**
   * 设置类别请求参数
   * @param category
   * @private
   */
  _setCategoryParam = (category) => {
    if (category === defaultPositionCategory) {
      this._deleteHomeListParams(this.categoryKey)
    } else {
      this._addHomeListParams(this.categoryKey, [category])
    }
  }

  /**
   * 重置过滤条件
   * @param category
   * @returns {{}}
   * @private
   */
  _reInitFilterArr = (category) => {
    const filterArr = this.flatList[this.currentIndex].filterArr
    const [, position] = filterArr
    if (defaultPositionCategory === category) {
      position.label = '职位'
    } else {
      position.label = category
      position.type = this.categoryKey
      position.value = [category]
    }
    return filterArr
  }

  _getHomeListParams = () => {
    const { landmark: { currentLocation } } = this.props
    const latitude = currentLocation && currentLocation.lat
    const longitude = currentLocation && currentLocation.lng
    const homeListParams = [
      {
        [this.pageKey]: 1,
        type: 0
      },
      {
        [this.pageKey]: 1,
        practiceLabel: 1
      },
      {
        [this.pageKey]: 1,
        type: 1
      }
    ]
    if (latitude && longitude) {
      homeListParams.forEach((item) => {
        item.latitude = latitude
        item.longitude = longitude
      })
    }
    return homeListParams
  }

  postFunc () {
    return homePostList
  }

  /**
   * 每一条的样式
   * @param item
   * @param index
   * @returns {XML}
   * @private
   */
  renderItem ({ item, index }) {
    const { landmark } = this.props
    return (
      <CustomButton onPress={this._jobClick} params={{ item, index }}>
        <JobCell
          style={{ paddingTop: ScaleS(index === 0 ? 25 : 40) }} item={item} landmark={landmark}
          threeDotPress={this._threeDotPress}/>
      </CustomButton>
    )
  }

  _threeDotPress = (item) => {
    getPostDetail({ params: { postId: item.id } }).then((data) => {
      const jobDetail = data.data
      const { isReport, collectionId } = jobDetail
      this.dotArr = []
      if (isReport === 0) { // 没有举报
        this.dotArr.push({
          label: '举报',
          type: 0
        })
      }
      if (collectionId) { // 已经收藏
        this.dotArr.push({
          label: '取消关注',
          type: 2,
          collectionId
        })
      } else {
        this.dotArr.push({
          label: '关注',
          type: 1
        })
      }
      this.dotArr.push({
        label: '不感兴趣',
        type: 3
      })
      this.threeDotPress(item)
    })
  }

  collection (params) {
    const { userId } = this.props
    return collectionPost({
      params: {
        postId: params.id,
        userId
      }
    })
  }

  unCollection (collectionId) {
    return cancelCollectionPost({
      params: {
        ids: collectionId.toString()
      }
    })
  }

  _jobClick = ({ item, index }) => {
    const blockCallback = () => {
      const dataArr = this.state[this.dataKeys[this.currentIndex]]
      const newDataArr = dataArr.filter((e) => {
        return e.id !== item.id
      })
      this.setState({ [this.dataKeys[this.currentIndex]]: newDataArr })
    }
    this.props.navigation.navigate('CJobdetail', {
      id: item.id,
      cityName: this.props.landmark.cityName,
      blockCallback
    })
  }

  componentWillFocus () {
  }

  componentDidMount () {
    super.componentDidMount()
    this.tabRefreshSubscription = DeviceEventEmitter.addListener(
      C_POSITION_REFRESH,
      this.tabRefreshClick
    )
    this.CPositionPageSubscription = DeviceEventEmitter.addListener(
      'CPositionPage',
      this._positionListener
    )
  }

  /**
   * 职位监听
   * @param position
   * @private
   */
  _positionListener = ({ position }) => {
    const { type, category } = position
    this.currentIndex = type
    const filterArr = this._reInitFilterArr(category)
    this.setState({ index: type, filterArr })
    this._setCategoryParam(category)
    this._onRequestRefresh(true)
  }

  componentWillUnmount () {
    super.componentWillUnmount()
    this.tabRefreshSubscription && this.tabRefreshSubscription.remove()
    this.CPositionPageSubscription && this.CPositionPageSubscription.remove()
    console.log('C---->HomePage--->componentWillUnmount')
  }

  tabRefreshClick = () => {
    // this._scrollToTopRefresh(false)
  }
}

export default CPositionPage

// https://github.com/Micjoyce/ScrollViewWithTabView
